import React, { Component ,useState} from 'react';
import { Form, Input, InputNumber, Button ,Upload, message , Modal ,Select} from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
import {apilink} from "../../api/apilink"
export default class add_goods extends Component {
    constructor(props){
        super(props)
    }
    state = {
        mainImageUrl:"",
        loading: false,
        values:"",
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        mainfileList:[],
        fileList: [],
        fromInfo:""
    }
   onFinish = (values) => {
        console.log(values);
        this.setState({
        fromInfo:values
        })
        this.addListGoods()
    }
    //向表list中添加数据 上架商品   ----- 添加的图片不能传到服务器上面 ，所以直接提前准备好图片，将图片路径传送过去
    addListGoods=()=>{
        let newarr = [];
        if(sessionStorage.getItem("userId")){
            console.log(this.state.fromInfo.user.mainImg.file.name);
            console.log(this.state.fileList)
            if(this.state.fileList.length){
                this.state.fileList.forEach(item=>{
                    newarr.push(`images/list/${item.name}`)
                })
            }
            console.log(newarr)
            console.log(newarr.join())
            // return;
            let usp = new URLSearchParams();
            usp.append("mainImg",`images/list/${this.state.fromInfo.user.mainImg.file.name}`)
            usp.append("title",this.state.fromInfo.user.title)
            usp.append("kind",this.state.fromInfo.user.kind)
            usp.append("color",this.state.fromInfo.user.color)
            usp.append("price",this.state.fromInfo.user.price)
            usp.append("detailsImg",newarr.join())
            usp.append("detailsProductInfo",this.state.fromInfo.user.detailsProductInfo)
            usp.append("productNumber",this.state.fromInfo.user.productNumber)
            usp.append("productInfo",this.state.fromInfo.user.productInfo)
            usp.append("productData",this.state.fromInfo.user.productData)
            apilink("/api/add_listGoods","post",usp).then((ok)=>{
                console.log(ok);
                if(ok.data.code === 200){
                        message.success('添加成功');//antd 气泡提示
                        this.setState({
                            fileList:[],
                            fromInfo:""
                        })
                }else{
                        message.warning('添加失败')
                }
                // if(ok.data == "add_success"){
                //     return
                // }
                // if(ok.data == "add_cf_success"){
                //     message.success('添加成功 +1');
                // }else{
                // }

            }).catch((err)=>{
                console.log(err)
            })

        }else{
            alert("您还未登录，请先登录")
            this.props.history.push("/login")
        }
    }

    getBase64Main(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }
    getBase64=(file)=>{
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
        });
      }
      handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        }

        this.setState({
        previewImage: file.url || file.preview,
        previewVisible: true,
        previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    handleChange = ({ fileList }) => this.setState({ fileList });
    // handleChangeMain = ({ mainfileList }) => this.setState({ mainfileList });

    handleChangeMain = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64Main(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,
              mainImageUrl:info.file.name
            }),
            console.log("图片路径",info.file.name),
          );
        }
      };
    beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    }
    //提交函数
    submFn=()=>{
        console.log("title")
    }
    render() {
        const { previewVisible, previewImage,mainfileList , fileList, previewTitle, loading, imageUrl} = this.state;
        
        const uploadButtonMain = (
            <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
        );
        const layout = {
            labelCol: {
              span: 8,
            },
            wrapperCol: {
              span: 16,
            },
          };
          const validateMessages = {
            required: '${label}必须填写',
            types: {
              email: '${label} is not a valid email!',
              number: '${label} is not a valid number!',
            },
            number: {
              range: '${label} must be between ${min} and ${max}',
            },
          };
          
        return (
            <div>
                {/* <h2>上传商品</h2> */}
                <Form {...layout} name="nest-messages" onFinish={this.onFinish.bind(this)} validateMessages={validateMessages}>
            <Form.Item
                name={['user', 'title']}
                label="主标题"
                rules={[
                {
                    // required: true,
                },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                name={['user', 'kind']}
                label="种类"
                rules={[
                {
                    // required: true,
                    type: 'string',
                },
                ]}
            >
            <Select>
                <Select.Option value="项链,xianlian">项链</Select.Option>
                <Select.Option value="链坠,lianzhui">链坠</Select.Option>
                <Select.Option value="套装,taozhuang">套装</Select.Option>
                <Select.Option value="耳环,erhuan">耳环</Select.Option>
                <Select.Option value="戒指,jiezhi">戒指</Select.Option>
                <Select.Option value="手链,shoulian">手链</Select.Option>
                <Select.Option value="热卖单品,all">热卖单品</Select.Option>
                <Select.Option value="手机壳,phone">手机壳</Select.Option>
                <Select.Option value="钥匙扣,key">钥匙扣</Select.Option>
                <Select.Option value="圆珠笔,pen">圆珠笔</Select.Option>
                
            </Select>
                {/* <Input /> */}
            </Form.Item>
            <Form.Item
                name={['user', 'color']}
                label="颜色"
                rules={[
                {
                    // required: true,
                    type: 'string',
                },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                name={['user', 'price']}
                label="价格"
                rules={[
                {
                    // required: true,
                    type: 'string',
                },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                name={['user', 'productData']}
                label="产品材料"
                rules={[
                {
                    // required: true,
                    type: 'string',
                },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                name={['user', 'priceNumber']}
                label="产品编号"
                rules={[
                {
                    // required: true,
                    type: 'string',
                },
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item name={['user', 'productInfo']} label="产品详情">
                <Input.TextArea />
            </Form.Item>
            <Form.Item name={['user', 'detailsProductInfo']} label="产品详情简介">
                <Input.TextArea />
            </Form.Item>
            <Form.Item name={['user', 'mainImg']} label="主图图片">
            <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                beforeUpload={this.beforeUpload}
                onChange={this.handleChangeMain}
            >
                {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButtonMain}
            </Upload>
            </Form.Item>
            <Form.Item name={['user', 'detailsImg']} label="详情图片">
                
            <Upload
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            listType="picture-card"
            fileList={fileList}
            onPreview={this.handlePreview}
            onChange={this.handleChange}
            >
            {fileList.length >= 6 ? null : uploadButton}
            </Upload>
            <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={this.handleCancel}
            >
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>

            </Form.Item>
            <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
                <Button type="primary" htmlType="submit" >
                添加
                </Button>
            </Form.Item>
            
            </Form>
            </div>
            
        )
    }
}
